/*
 * @Author: yanjikun
 * @Date: 2022-05-11 14:01:20
 * @LastEditors: yanjikun
 * @LastEditTime: 2022-05-11 14:07:38
 * @Description: file content
 */

import { encrypt, decrypt } from 'crypto-js/aes'
import { parse } from 'crypto-js/enc-utf8'
import pkcs7 from 'crypto-js/pad-pkcs7'
import ECB from 'crypto-js/mode-ecb'
import UTF8 from 'crypto-js/enc-utf8'
export interface EncryptionParams {
  key: string
  iv: string
}

export class AesEncryption {
  private key: string | CryptoJS.lib.WordArray | undefined
  private iv: CryptoJS.lib.WordArray | undefined

  constructor(opt: Partial<EncryptionParams> = {}) {
    const { key, iv } = opt
    if (key) {
      this.key = parse(key)
    }
    if (iv) {
      this.iv = parse(iv)
    }
  }

  get getOptions() {
    return {
      mode: ECB,
      padding: pkcs7,
      iv: this.iv,
    }
  }

  encryptByAES(cipherText: string) {
    return encrypt(cipherText, this.key!, this.getOptions).toString()
  }

  decryptByAES(cipherText: string) {
    return decrypt(cipherText, this.key!, this.getOptions).toString(UTF8)
  }
}
